/*****************************************************************************
 *   Copyright 2005 Tim A Wang
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 ****************************************************************************/
package com.jb.web.model;

import com.jb.framework.ModelBean;
import com.jb.framework.PersistentContext;
import com.jb.framework.pm.XMLPersistentManager;
import com.jb.web.application.configuration.Config;
import com.jb.web.bean.custom.FileNode;
import com.jb.web.context.WebContext;
import com.jb.web.session.SessionUser;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class ApplicationConfig extends ModelBean {
    static private Log log = LogFactory.getLog(ModelBean.class.getName());

    private Date creationDate;
    private Date expiryDate;
    private String author;
    private String authorId;
    private String homePage;
    private String logo;
    private String name;
    private String title;
    private int access;

    static Map apps = new HashMap();

    public void setAccess(int access) {

        this.access = access;
    }

    public int getAccess() {
        return access;
    }

    public String getAuthor() {
        return author;
    }

    public void setExpiryDate(Date expiryDate) {
        this.expiryDate = expiryDate;
    }

    public Date getExpiryDate() {
        return expiryDate;
    }

    public void setHomePage(String homePage) {
        this.homePage = homePage;
    }

    public String getHomePage() {
        return homePage;
    }

    public void setLogo(String logo) {
        this.logo = logo;
    }

    public String getLogo() {
        return logo;
    }

    public void addVariable(Variable variable) throws Exception {
        this.addChild(variable);
    }

    public void create(PersistentContext ctx) {
        WebContext pCtx = (WebContext)ctx;
        try {
            if (pCtx.getSession() != null) {
                SessionUser user = pCtx.getSession().getUser();
                setAuthor(user.getScreenName());
                setAuthorId(user.getId());
            }
            pm.save(this);

            if (pCtx.getSession() != null) {
                pCtx.getSession().setApplicationName(getId());
            }
        } catch (Exception e) {
            pCtx.renderResponse();
            pCtx.addErrorMessage(this, e.getMessage());
        }
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public void setAuthorId(String authorId) {
        this.authorId = authorId;
    }

    public String getAuthorId() {
        return authorId;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    public void delete(PersistentContext ctx) {
        WebContext pCtx = (WebContext)ctx;
        String user = pCtx.getSession().getUser().getId();

        if (getAuthorId()!=null && !user.equals(this.getAuthorId())) {
            pCtx.addErrorMessage(this, "Operation is not allowed for " + user);

            return;
        }

        FileNode file = FileNode.createFileNode(Config.getInstance().getApplicationTop(), this.getId(), false, "*");

        //delete all pages as well
        if (file.delete()) {
            try {
                pm.delete(this);
                super.delete(pCtx);
            } catch (Throwable t) {
                if(log.isErrorEnabled())
                    log.error(this, t);
                //
            }
        }
    }

    //a list of applications
    private static Map applications = new HashMap();

    public static ModelBean findById(Class clazz, String id) {
        Object bean = applications.get(id);
        if (bean == null) {
            bean = pm.findById(clazz, id);
            applications.put(id, bean);
        }
        return (ModelBean)bean;
    }

    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }

    public Date getCreationDate() {
        return creationDate;
    }

    public boolean load() {
        try {
            pm.load(this);
            return true;
        } catch (Throwable e) {
            return false;
        }
    }

    static XMLPersistentManager pm = new XMLPersistentManager(Config.getInstance().getConfigTop());

    public String toString() {
        return getTitle();
    }

    public void update(PersistentContext ctx) {
        WebContext pCtx = (WebContext)ctx;

        if (pCtx.getSession() != null) //if it is offline, we allow access
        {
            String user = pCtx.getSession().getUser().getId();

            if (!user.equals(getAuthorId())&&getAuthorId()!=null) {
                pCtx.addErrorMessage(this, "Operation is not allowed for " + user);
                if(log.isErrorEnabled())
                    log.error("Operation is not allowed for " + user);
                return;
            }
        }
        pm.save(this);
    }

    Map attributes = new HashMap();

    public List getVariables() {
        return this.getChildren();
    }

    public Map getAttributes() {
        return attributes;
    }
}
